import hmac
import hashlib
import base64

from time import mktime
from datetime import datetime
from urllib.parse import urlencode, urlparse
from wsgiref.handlers import format_date_time

# 在此修改鉴权信息
APP_ID = ""
API_KEY = ""
API_SECRET = ""


class XFYunAuth(object):
    def __init__(self, XFYun_URL: str):
        """
        初始化认证信息,

        """
        self.APP_ID = APP_ID
        self.API_Key = API_KEY
        self.API_Secret = API_SECRET
        self.url = XFYun_URL
        self.host = urlparse(XFYun_URL).netloc
        self.path = urlparse(XFYun_URL).path
        # 公共参数(common)
        self.CommonArgs = {"app_id": self.APP_ID}
    def create_url(self):
        """
        创建科大讯飞的鉴权url,
        https://www.xfyun.cn/doc/spark/spark_zh_iat.html
        """

        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))
        # 检测并修改 self.host
        if self.host == "tts-api.xfyun.cn":
            self.host = "ws-api.xfyun.cn"

        # 拼接字符串
        signature_origin = "host: " + self.host + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + self.path + " HTTP/1.1"
        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(
            self.API_Secret.encode("utf-8"),
            signature_origin.encode("utf-8"),
            digestmod=hashlib.sha256,
        ).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")

        authorization_origin = f'api_key="{self.API_Key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha}"'

        authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(
            encoding="utf-8"
        )
        # 将请求的鉴权参数组合为字典
        v = {"authorization": authorization, "date": date, "host": self.host}
        # 拼接鉴权参数，生成url
        url = self.url + "?" + urlencode(v)
        print("date: ", date)
        print("v: ", v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释，比对相同参数时生成的url与自己代码生成的url是否一致
        print("websocket url :", url)
        return url
